package com.meshnetics.gb.stack.mac.io;

import com.meshnetics.gb.util.ToStringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Sergey Klimenko (sklimenko@meshnetics.com)
 */
public class LoggerOutputStream extends OutputStream {
    private static final Log log = LogFactory.getLog(LoggerOutputStream.class);

    private OutputStream outputStream;

    public LoggerOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void write(byte b[]) throws IOException {
        outputStream.write(b);
        if (log.isDebugEnabled()) {
            log.debug("bytes send to port: " + ToStringUtil.toString(b));
        }
    }

    public void write(byte b[], int off, int len) throws IOException {
        outputStream.write(b, off, len);
        if (log.isDebugEnabled()) {
            log.debug("bytes send to port: " + ToStringUtil.toString(b, off, len));
        }
    }

    public void write(int b) throws IOException {
        outputStream.write(b);
        if (log.isDebugEnabled()) {
            log.debug("bytes send to port: " + ToStringUtil.toString(new byte[]{(byte) b}));
        }
    }

    public void close() throws IOException {
        outputStream.close();
        if (log.isDebugEnabled()) {
            log.debug("port output stream closed");
        }
    }

    public void flush() throws IOException {
        outputStream.flush();
        if (log.isDebugEnabled()) {
            log.debug("flush data to port");
        }
    }
}
